<template>
    <div class="login">
      <van-form @submit="handleLoginSubmit" ref="loginFormRef" :rules="loginRules">
        <van-cell-group inset>
          <van-field
            v-model="loginData.email"
            name="username"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model="loginData.password"
            type="password"
            name="password"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
      
    </div>
  </template>
  <script setup  lang="ts">
    import { ref,computed } from 'vue';
    import type { FormInstance } from 'vant';
    import  router  from '@/router';
    import { useI18n } from 'vue-i18n';
    import {
        useUserStore,
      } from "@/stores";
    import CryptoJS from "crypto-js";
    import  {AuthAPI,
        type LoginData,
    } from "@/request/api";
    const { t } = useI18n();

    const loginRules = computed(() => {
        return {
            username: [
                {
                    required: true,
                    trigger: "blur",
                    message: t("用户"),
                },
            ],
            password: [
                {
                    required: true,
                    trigger: "blur",
                    message: t("密码"),
                },
                {
                    min: 6,
                    message: t("密码"),
                    trigger: "blur",
                },
            ],
        
        };
    });
    /**
    * 登录相关
    */
    const loginData = ref<LoginData>({
        email: "",
        password: "",
        captchaKey: "",
        captchaCode: "",
    });
    const loginFormRef = ref<FormInstance>();
    const username = ref('');
    const password = ref('');
    const captchaBase64 = ref(); // 验证码图片Base64字符串
//     const onSubmit = async (values: any) => {
//   if (values.password !== values.password2) {
//     showNotify({ type: 'warning', message: mb_t('两次输入的密码不一致！') });
//     return;
//   }
//   const pwdLevel: string = tenantInfo.value.sysOptions.PASSWORD_MODE || '1';
//   if (!checkPwd(values.password, pwdLevel)) {
//     showNotify({ type: 'warning', message: mb_t(pwdLevelText(pwdLevel)) });
//     return;
//   }
//   console.log(values, 'onSubmit');
//   loading.value = true;
//   try {
//     let res = await forgetPassword(pick(values, ['password', 'phone', 'smsCode']));
//     if (res && res.response_code === '9999') {
//       showNotify({ type: 'success', message: mb_t('密码修改成功！') });
//       await promiseTimeout(300);
//       visible.value = true;
//     }
//   } catch (err: any) {
//     err?.info && showNotify({ type: 'danger', message: mb_t(err.info) });
//   } finally {
//     loading.value = false;
//   }
// };
    /** 获取验证码 */
    const getCaptcha = async () =>{
        await AuthAPI.getCaptcha().then((data) => {
            loginData.value.captchaKey = data.captchaKey;
            captchaBase64.value = data.captchaBase64;
        });
    }
    /** 登录表单提交 */
    const handleLoginSubmit = async (values: any) => {
        console.log(values, 'onSubmit');
        let data = {
          id: 1
        };
        await AuthAPI.scanLogin(data).then(async(res) => {
            console.log('登录',res);
            // 新增token存储逻辑
            const token = res.accessToken || ''
            localStorage.setItem('ACCESS_TOKEN', token)
            localStorage.setItem('userInfo', JSON.stringify(res.userInfo))
            useUserStore().token = token
            // 需要调用store的login方法更新状态
            useUserStore().login('用户名', token) // 添加用户名参数
        // // 跳转到登录前的页面
        // const { path, queryParams } = parseRedirect();
        // router.push({ path: path, query: queryParams });
        // 登录成功后跳转回原页面
            const redirect = router.currentRoute.value.query.redirect || '/example'
            await router.replace(redirect as string) // 使用replace避免后退到登录页
            window.location.href = redirect as string // 硬刷新确保状态同步
        });
        
        // // loading.value = true;
        //     let password = loginData.value.password;
        //     let key = CryptoJS.enc.Utf8.parse("x8krb4xkmbonnua2");
        //     let encrypted = CryptoJS.AES.encrypt(password, key, {
        //         mode: CryptoJS.mode.ECB,
        //         padding: CryptoJS.pad.Pkcs7,
        //     });
        //     await getCaptcha().then(() => {
        //         console.log(loginData.value, 'loginData.value');
        //         const tempLoginData: LoginData = {
        //             email: loginData.value.email,//用户名
        //             password: encrypted.toString(),//密码
        //             captchaKey: loginData.value.captchaKey,//获取验证码
        //             captchaCode: '123',//输入的验证码
        //         };
        //         AuthAPI
        //             .login(tempLoginData)
        //             .then(async (res) => {
        //                 console.log(res, 'login');
        //                 // 新增token存储逻辑
        //                 const token = res.accessToken || '我是token'
        //                 localStorage.setItem('ACCESS_TOKEN', token)
        //                 useUserStore().token = token
        //                 // 需要调用store的login方法更新状态
        //                 useUserStore().login('用户名', token) // 添加用户名参数
        //             // // 跳转到登录前的页面
        //             // const { path, queryParams } = parseRedirect();
        //             // router.push({ path: path, query: queryParams });
        //             // 登录成功后跳转回原页面
        //                 const redirect = router.currentRoute.value.query.redirect || '/example'
        //                 await router.replace(redirect as string) // 使用replace避免后退到登录页
        //                 window.location.href = redirect as string // 硬刷新确保状态同步
        //                 // router.push(redirect as string).then(() => {
        //                 //     // 强制刷新页面确保pinia状态同步
        //                 //     location.reload()
        //                 // });
        //             })
        //             .catch(() => {
        //             // getCaptcha();
        //             })
        //             .finally(() => {
        //             // loading.value = false;
        //             });
        //     });
           
        // return;


        // loginFormRef.value?.validate((valid: boolean) => {
        //     console.log('valid', valid);
        //     if (valid) {
        //     loading.value = true;
        //     let password = loginData.value.password;
        //     let key = CryptoJS.enc.Utf8.parse("x8krb4xkmbonnua2");
        //     let encrypted = CryptoJS.AES.encrypt(password, key, {
        //         mode: CryptoJS.mode.ECB,
        //         padding: CryptoJS.pad.Pkcs7,
        //     });

        //     const tempLoginData: LoginData = {
        //         email: loginData.value.email,
        //         password: encrypted.toString(),
        //         captchaKey: loginData.value.captchaKey,
        //         captchaCode: loginData.value.captchaCode,
        //     };
        //     AuthAPI
        //         .login(tempLoginData)
        //         .then(async () => {
        //         // 跳转到登录前的页面
        //         const { path, queryParams } = parseRedirect();
        //         router.push({ path: path, query: queryParams });
        //         })
        //         .catch(() => {
        //         getCaptcha();
        //         })
        //         .finally(() => {
        //         loading.value = false;
        //         });
        //     }
        // });
    }
  </script>
  <style>
  @media (min-width: 1024px) {
    .my {
      min-height: 100vh;
      display: flex;
      align-items: center;
    }
  }
  </style>
  